import { getToken, setToken } from '@/store/user/utils';
import { getDetails, getUserProfile, userRouters, type UserRouter } from './user';
import router from '@/router';
import { localComponents, pageConfig } from '@/initial';
import { LOCALSTORAGE_ENUM, SYS_THEME } from '@/enum/system';
import useUserStore from '@/store/user';
import { parentRouters } from '@/views/admin/layout/data/router';

export const userMenus = ref<UserRouter[]>([]);

export const clearMenus = async () => {
  localStorage.removeItem(LOCALSTORAGE_ENUM.USER_ROUTERS);
  await getUserRouters();
  window.location.reload();
};

export const getUserRouters = async () => {
  let localRouters = localStorage.getItem(LOCALSTORAGE_ENUM.USER_ROUTERS);
  let routers: UserRouter[] = [];
  const { data } = await userRouters();
  if (!data.data) return;
  if (localRouters) {
    routers = JSON.parse(localRouters);
  } else {
    routers = data.data;
    localStorage.setItem(LOCALSTORAGE_ENUM.USER_ROUTERS, JSON.stringify(routers));
  }
  userMenus.value = routers;

  const filterTree = (data: UserRouter[]) => {
    return data.map(item => {
      if (item.children) {
        filterTree(item.children);
      } else {
        Object.keys(localComponents.value).forEach(e => {
          if (e === item.path) {
            let { path, component } = localComponents.value[e];

            router.addRoute('index', {
              path: `/index/${path}`,
              component,
              name: item.component,
              meta: {
                ...item.meta,
              },
            });
          }
        });
      }
      return item;
    });
  };

  filterTree(routers);
};

/* User Logout */
export const logoff = () => {
  setToken('');
  localStorage.removeItem(LOCALSTORAGE_ENUM.USER_ROUTERS);
  localStorage.setItem(LOCALSTORAGE_ENUM.LANG, 'en');
  // localStorage.removeItem(LOCALSTORAGE_ENUM.PAGE);
  localStorage.removeItem(LOCALSTORAGE_ENUM.USER);
  pageConfig.value.algorithm = SYS_THEME.LIGHT;
  parentRouters.value = [];
  router.push('/login');
};

export const getProfile = async () => {
  const token = getToken();
  if (token) {
    const { data } = await getUserProfile();
    const store = useUserStore();
    store.$state.userInfo = data.data.user;
    store.$state.paths = data.data.paths;
    localStorage.setItem(LOCALSTORAGE_ENUM.LANG, data.data.user.lang);
  }
};

interface AccountInfo {
  logo: string;
  title: string;
  theme: SYS_THEME;
}
export const getAccountInfo = async (): Promise<AccountInfo> => {
  const { data } = await getDetails();
  const info: AccountInfo = JSON.parse(data.data);
  document.title = info?.title || 'ESL';
  pageConfig.value.algorithm = info?.theme || SYS_THEME.LIGHT;
  return info;
};
export const getParentPaths = (data: UserRouter[], path: string): UserRouter[] => {
  if (!data) return [];
  const findParent = (nodes: UserRouter[], targetPath: string): UserRouter[] => {
    for (const node of nodes) {
      if (node.path === targetPath) {
        return [node];
      }
      if (node.children?.length > 0) {
        const result = findParent(node.children, targetPath);
        if (result.length > 0) {
          return [node, ...result];
        }
      }
    }
    return [];
  };

  return findParent(data, path);
};

export const findUserRouter = (
  root: UserRouter[],
  target: string,
  key: 'path' | 'id' = 'path',
): UserRouter | null => {
  const find = (nodes: UserRouter[]): UserRouter | null => {
    if (!nodes) return null;
    for (const node of nodes) {
      if (node[key] === target) {
        return node;
      }
      const childResult = find(node.children);
      if (childResult) {
        return childResult;
      }
    }
    return null;
  };

  return find(root);
};
